import axios from 'axios'
import Qs from 'qs'
import router from '@/router/index'
import store from '@/store/index'
import { Message } from 'element-ui'
// 判断登录是否失效
import { GetInfo } from '@/server/login'
// 跳转
const toLogin = () => {
    router.push({
        path: '/login',
        query: {
            redirect: router.currentRoute.fullPath
        }
    })
}

const api = axios.create({
    baseURL: process.env.VUE_APP_API_PROXY,
    timeout: 0
    // responseType: 'json'
    // withCredentials: true
})

api.interceptors.request.use(
    request => {
        if (request.url !== '/login') {
            if (store.getters['user/isLogin']) {
                request.headers["Authorization"] = "Bearer " + store.state.user.token
            }
        }
        return request
    }
)

api.interceptors.response.use(
    response => {
        if (response.data.success === false) {
            let errmore = response.data.data.errmore
            let index = errmore.indexOf("\n")
            let error = errmore.slice(0, index)
            Message.error(error)
            return Promise.reject(response.data)
        }
        if (response.data.code == 401) {
            // 如果接口请求时发现 token 失效，则立马跳转到登录页
            if(response.config.url !== '/getInfo') {
                GetInfo().then(userInfo => {
                    if( userInfo.code !== 401 ) return
                    store.dispatch('user/logout').then(() => {
                        router.push({
                            path: '/login',
                            query: {
                                redirect: router.currentRoute.fullPath
                            }
                        })
                    })
                })
            }
        }
        return Promise.resolve(response.data)
    },
    error => {
        Message({
            message: '请求错误',
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default api
